package tchk.xyz.lingyuntutorminiprogram.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import tchk.xyz.lingyuntutorminiprogram.entity.SysPermission;
import tchk.xyz.lingyuntutorminiprogram.service.ISysPermissionService;
import tchk.xyz.lingyuntutorminiprogram.utils.Result;

@RestController
@RequestMapping("/api/admin/permission")
@PreAuthorize("hasAuthority('admin:permission:manage')") // 整个Controller都需要权限
public class PermissionController {

    @Autowired
    private ISysPermissionService permissionService;

    /**
     * 分页查询权限列表
     */
    @GetMapping("/list")
    public Result<Page<SysPermission>> getPermissionList(@RequestParam(defaultValue = "1") long current,
                                                         @RequestParam(defaultValue = "10") long size) {
        Page<SysPermission> page = new Page<>(current, size);
        return Result.success(permissionService.page(page));
    }

    /**
     * 新增权限
     */
    @PostMapping
    public Result<Void> addPermission(@RequestBody SysPermission permission) {
        // 可以在这里加一些校验，比如code不能重复
        permissionService.save(permission);
        return Result.success();
    }

    /**
     * 修改权限
     */
    @PutMapping
    public Result<Void> updatePermission(@RequestBody SysPermission permission) {
        permissionService.updateById(permission);
        return Result.success();
    }

    /**
     * 删除权限
     */
    @DeleteMapping("/{id}")
    public Result<Void> deletePermission(@PathVariable Long id) {
        // TODO: 在删除前，最好检查一下这个权限是否已被某些角色使用
        permissionService.removeById(id);
        return Result.success();
    }
}